package zh;

import java.awt.geom.Point2D;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.logging.Logger;
import robocode.*;
import zh.logging.MyLogger;

/**
 *
 * @author zheismann
 */
public class EnemyManager
{
    private static MyLogger logger = MyLogger.getLogger(EnemyManager.class.getName());
    static
    {
        logger.setEnabled(false);
    }
    private HashMap<String, Enemy> enemyMap;
    private final static EnemyManager instance = new EnemyManager();
    private EnemyManager()
    {
        enemyMap = new HashMap<String, Enemy>();
    }
    
    public static final EnemyManager getInstance()
    {
        return instance;
    }
    
    public void processEvent(ScannedRobotEvent scanned, Point2D enemyLocation)
    {
        Enemy enemy = null;
        if (enemyMap.containsKey(scanned.getName()))
        {
            logger.log("EXISTING Enemy: " + scanned.getName());
            enemy = enemyMap.get(scanned.getName());
            enemy.updateData(scanned, enemyLocation);
        }
        else
        {
            logger.log("NEW Enemy: " + scanned.getName());
            enemy = new Enemy(scanned, enemyLocation);
            enemyMap.put(scanned.getName(), enemy);
        }
    }
    
    public void processEvent(RobotDeathEvent killed)
    {
        if (enemyMap.containsKey(killed.getName()))
        {
            enemyMap.remove(killed.getName());
        }        
    }
    public void processEvent(DeathEvent event)
    {
        enemyMap.clear();
    }
    public void processEvent(WinEvent event)
    {
        enemyMap.clear();
    }
    
    public void processEvent(BulletMissedEvent event)
    {

    }
    public void processEvent(BulletHitEvent event)
    {
//        System.out.println("event.getName(): " + event.getName());
//        System.out.println("(enemyMap.containsKey(event.getName())): " + (enemyMap.containsKey(event.getName())));
        if (enemyMap.containsKey(event.getName()))
        {
            Enemy enemy = enemyMap.get(event.getName());
            if (enemy != null)
            {
                enemy.bulletHitMe();
            }
        }
    }
    
    public boolean hasEnemy()
    {
        return enemyMap.keySet().size() > 0;
    }
    
    public int getNumberOfKnownEnemies()
    {
        return enemyMap.keySet().size();
    }
    
    public Collection<Enemy> getAllEnemies()
    {
        return Collections.unmodifiableCollection(enemyMap.values());
    }
    
    public Enemy getClosestEnemy()
    {
        Enemy closestEnemy = null;
        for (String name : enemyMap.keySet())
        {
            Enemy enemy = enemyMap.get(name);
            if (closestEnemy == null || enemy.getDistance() < closestEnemy.getDistance())
            {
                closestEnemy = enemy;
            }
        }
        return closestEnemy;
    }
    
    public Enemy getEnemy(String name)
    {
        return enemyMap.get(name);
    }
}
